/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.miit.elearning.hibernate.dao;

import java.sql.Timestamp;
import java.util.List;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dto.Message;
import ru.miit.elearning.hibernate.dto.UserIdentity;

/**
 *
 * @author Cyclone
 */
public class MessageDAO extends GenericDAO {

    public MessageDAO(Session session) {
        super(session);
    }

    public List<Message> findMessagesByUser(int userId) {
        return session.createQuery("from Message WHERE userIdentityByIdRecipient.account = :id_recipient ORDER BY creationDate DESC")
                .setParameter("id_recipient", userId)
                // .setFirstResult(0)
                .setMaxResults(10)
                .list();
    }

    public Message addMessage(int idSender, int idRecipient, String subject, String content) {
        Message m = new Message();
//        m.setIdSender(idSender);
        m.setUserIdentityByIdSender((UserIdentity)session.get(UserIdentity.class, idSender));
//        m.setIdRecipient(idRecipient);
        m.setUserIdentityByIdRecipient((UserIdentity)session.get(UserIdentity.class, idRecipient));
        m.setSubject(subject);
        m.setContent(content);
        m.setCreationDate(new Timestamp(System.currentTimeMillis()));

        int idMessage = (Integer)session.save(m);
        return (Message)session.get(Message.class, idMessage);
    }

    public String deleteMessage(int idMessage) {
        Message m = (Message)session.get(Message.class, idMessage);
        String subject = m.getSubject();

        session.delete(m);
        return subject;
    }

    /**
     * Performs check if userId is a recipient of messageId
     * @param userId
     * @param messageId
     * @return
     */
    public boolean isUserRecipientsMessage(int userId, int messageId) {
        Message m = (Message)session.get(Message.class, messageId);
        return(m.getUserIdentityByIdRecipient().getAccount() == userId);
        
    }

    public Message findMessage(int messageId) {
        return (Message)session.get(Message.class, messageId);
    }

    public Message findLastMessageByUser(Integer currentUserId) {
        return (Message)session.createQuery("from Message WHERE userIdentityByIdRecipient.account = :id_recipient ORDER BY creationDate DESC")
                .setParameter("id_recipient", currentUserId)
                .setMaxResults(1)
                .uniqueResult();
    }

    



    /*
    public Message findMessage(int messageId) {
        return (Message)session.get(Message.class, messageId);
    }
    */
}
